<script>
import {ref} from 'vue';
import http from '@/utils/api.js'
import router from "@/router/index.js"


export default {
  setup() {
    // const router = useRouter()
    const password = ref('')
    const username = ref('')
    //错误
    const usernameError = ref('');
    const passwordError = ref('');
    //校验
    const validateUsername = () => {
      usernameError.value = username.value ?
          (username.value.length >= 6 ? '' : '用户名长度至少为 6 个字符') : '不能为空';
    };

    const validatePassword = () => {
      passwordError.value = password.value ?
          (password.value.length >= 6 ? '' : '密码长度至少为 6 个字符') : '不能为空';
    };

    const handleLogin = async () => {
      validateUsername();
      validatePassword();

      if (usernameError.value || passwordError.value) {
        return;
      }
      try {
        const response = await http.post("/user/login", {
          username: username.value,
          password: password.value
        });

        console.log( "sda"+response);

        if (response.code === 200 && response.message.toLowerCase().includes("成功")) {
          // 解构时确保data存在
          const { token, userId, username, level } = response.data;
          if (token && userId && username) {
            localStorage.setItem('userToken', token);
            localStorage.setItem('username', username);
            localStorage.setItem('userId', userId);
            localStorage.setItem('level',level);
            await router.push('/dashboard');
          } else {
            console.error("Missing data fields in response:", response.data);
          }
        } else {
          alert(`登录失败: ${response.message}`);
          console.error("Login failed with message:", response.message);
        }
      } catch (err) {
        console.error("Error during login:", err);
      }
    };

    return {
      username,
      password,
      handleLogin,
      validateUsername,
      validatePassword,
      usernameError,
      passwordError,
    };
  }
}

</script>

<template>
  <div style="display: flex;align-items: center;justify-content: center;height: 100vh;">
    <div
        style="background-color: white;padding: 40px;border-radius: 8px;box-shadow: 0 4px 8px rgba(0,0,0,0.1);max-width: 400px;width: 100%"
    >
      <h1
          style="text-align: center;color: #d81b60;font-size: 24px;margin-bottom: 20px;"
      >登录</h1>
      <p
          style="text-align: center;color: #666;font-size: 14px;margin-bottom: 20px;"
      >每一次登录都是与你的邂逅。</p>
      <form
          style="display: flex; flex-direction: column;" @submit.prevent
      >
        <div class="input-container">
          <input
              type="text"
              v-model="username"
              placeholder="用户名"
              @blur="validateUsername"
          />
          <div v-show="usernameError" class="error-message">
            {{ usernameError }}
          </div>
        </div>
        <div class="input-container">
          <input
              type="password"
              v-model="password"
              placeholder="密码"
              @blur="validatePassword"
          />
          <div v-show="passwordError" class="error-message">
            {{ passwordError }}
          </div>
        </div>
        <div
            style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px; margin-bottom: 20px;"
        >
          <label style="font-size: 14px; color: #666;">
            <input type="checkbox" style="margin-right: 5px"/>
            记住密码
          </label>
          <a href="/register" style="font-size: 14px; color: #d81b60; text-decoration: none;">
            注册
          </a>
        </div>
        <button
            type="button"
            @click="handleLogin"
            style="margin-top: 10px;"
        >
          登录
        </button>
      </form>

    </div>

  </div>

</template>

<style scoped>
.input-container {
  position: relative; /* 使错误信息可以绝对定位在输入框下方 */
  margin-bottom: 28px; /* 增加输入框之间的间距 */
}
form{
  width: 280px;
  height: 300px;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  width: 100%;
}

button {
  background-color: #d81b60;
  color: white;
  padding: 10px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  width: 100%;
}

/* 错误提示样式 */
.error-message {
  position: absolute; /* 绝对定位，使其显示在输入框下方 */
  color: red;
  font-size: 12px;
  margin-top: 5px; /* 增加提示框上方的间距，确保不重叠 */
  left: 0;
  width: 100%;
}

form {
  display: flex;
  flex-direction: column;
}

form input {
  margin-bottom: 10px;
}

form button {
  margin-top: 20px;
}
</style>
